<?php

namespace App\Http\Middleware;

use App\Library\Service\DB\TransactionMonitorService;
use Closure;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class EasyWeb
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        self::startDebug();
        $response = $next($request);
        return self::modifyResponse($request, $response);
    }


    /**
     * 开启调试
     */
    private function startDebug()
    {
        list($usec, $sec) = explode(' ', microtime());
        $start_exec_time = (float)$usec + (float)$sec;
        define('START_EXEC_TIME', $start_exec_time);
        global $EASY_REQUEST_ID;
        $EASY_REQUEST_ID = md5(time() . easy_random(10));
        $easy_debug = isset($_GET['easy_debug']) && (int)$_GET['easy_debug'] != 0 ? (int)$_GET['easy_debug'] : $_COOKIE['easy_debug'] ?? 0;
        if ($easy_debug > 0) {
            //进入调试模式
            if (!defined('EASY_DEBUG')) {
                define('EASY_DEBUG', $easy_debug);
            }
            $debugbar = debugbar();
            if (!$debugbar->isEnabled()) {
                config(['debugbar.enabled' => true]);
                $debugbar->enable();
            }
            if ($easy_debug == 1 && function_exists('xhprof_enable')) {
                xhprof_enable(XHPROF_FLAGS_NO_BUILTINS | XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY);
            }
        }
        global $IS_API;
        if ($IS_API) {
            $debugbar = debugbar();
            if ($debugbar->isEnabled()) {
                config(['debugbar.enabled' => false]);
                $debugbar->disable();
            }
        }
    }

    /**
     * Modify the response and inject the debugbar (or data in headers)
     * @param Request $request
     * @param Response $response
     * @return Response
     */
    private function modifyResponse(Request $request, Response $response)
    {
        $visit_path = '';
        if (\Route::getCurrentRoute()) {
            $visit_path = \Route::getCurrentRoute()->uri();
            $visit_path = ltrim($visit_path, '/');
        }
        global $IS_API;
        if ($IS_API) {
            return $response;
        }
        if (str_contains($visit_path, '_debugbar')) {
            return $response;
        }
        global $SQL_LOG;
        global $EASY_REQUEST_ID;
        if (!empty($SQL_LOG) && (defined('IS_WEB') || IS_WEB == 1)) {
            $session = \Session::all();
            $param = $request->request->all();
            unset($param['password']);
            $log_data = ['url' => easy_get_current_url(), 'session' => $session, 'request' => $param, 'request_id' => $EASY_REQUEST_ID,];
            $sql_use_time = 0;
            if (!is_array($SQL_LOG)) $SQL_LOG = [];
            foreach ($SQL_LOG as $item) {
                $sql_use_time += $item['time'];
            }
            $log_data['sql_use_time'] = round($sql_use_time / 1000, 4);
            $log_data['sql_list'] = $SQL_LOG;
            easy_log('web_log', $log_data);
        }
        TransactionMonitorService::requestEnd([
            'request_id' => $EASY_REQUEST_ID,
            'visit_path' => $visit_path,
            'post' => $_POST,
            'get' => $_GET
        ]);
        //内存
        $memory = round(memory_get_peak_usage() / (1024 * 1024), 2);
        //执行用时
        $use_time = 0;
        if (defined('START_EXEC_TIME')) {
            list($usec, $sec) = explode(' ', microtime());
            $end_exec_time = ((float)$usec + (float)$sec);
            $use_time = round($end_exec_time - START_EXEC_TIME, 4);
        }
        if (!defined('EASY_DEBUG')) {
            define('EASY_DEBUG', 0);
        }
        $easy_debug = EASY_DEBUG;
        if ($easy_debug <= 0) {
            return $response;
        }
        //性能分析
        $run_id = 0;
        $run_url = '';
        if ($easy_debug == 1) {
            if (function_exists('xhprof_enable')) {
                $xhprof_data = xhprof_disable();
                $xhprof_runs = new \XHProfRuns_Default();
                $run_id = $xhprof_runs->save_run($xhprof_data, "easy");
                $run_url = 'http://' . $_SERVER['HTTP_HOST'] . '/xhprof/xhprof_html/index.php?run=' . $run_id . '&source=easy';
            }
        }
        $content = $response->getContent();
        if ($request->isXmlHttpRequest()) {
            $easy_data = ['run_id' => $run_id, 'run_url' => $run_url, 'memory' => $memory, 'use_time' => $use_time];
            $content = json_decode($content, true);
            if (is_array($content) || !isset($content[0])) {
                $content['easy_debug'] = $easy_data;
                $content = json_encode($content);
                $response->setContent($content);
            }
        } elseif ($response->headers->has('Content-Type') && str_contains($response->headers->get('Content-Type'), 'html') && $request->getRequestFormat() === 'html') {
            $easy_html = '<div class="alert alert-warning" style="position: fixed;left: 300px;bottom: 10px;">';
            if (!empty($run_id)) {
                $easy_html .= '<a target="_blank" href="' . $run_url . '">性能</a>&nbsp;&nbsp;&nbsp;';
            }
            $easy_html .= '内存:' . $memory . 'MB&nbsp;&nbsp;&nbsp;';
            $easy_html .= '用时:' . $use_time . '秒';
            $easy_html .= '</div>';
            $pos = strripos($content, '</body>');
            if (false !== $pos) {
                $content = substr($content, 0, $pos) . $easy_html . substr($content, $pos);
            } else {
                $content = $easy_html . $content;
            }
            $response->setContent($content);
        }
        return $response;
    }
}
